<?php
/**
 * Created by PhpStorm.
 * User: xudongsheng
 * Date: 2017/9/4
 * Time: 下午8:32
 */
namespace app\admin\model;

use think\Model;
use think\Validate;

class Admin extends Model
{
//    protected $insert = [
//        'login_time'    =>  '',
//        'login_ip'      =>  '',
//        'is_lock'       =>  1,
//        'encrypt'       => ''
//    ];

    const USER_KEY_STR  = 'userAdmin';

    protected $autoWriteTimestamp = true;

    /** 验证 登录
     * @return array
     */
    public static function checkLogin(){
        /**
         * 表单 验证
         */
        if (!($validate = validate('Admin'))->scene('login')->check(input('post.'))){
            return ['error' =>  true,'message'  =>  $validate->getError()];
        }
        /**
         * 数据库查询
         */
        $user  =    self::get(['username'=>input('post.username')]);
        if ( !($user AND ($user->password == md5($user->encrypt.input('post.password')))) ){
            return ['error' =>  true,'message'  =>  '用户名或密码错误！'];
        }
        /**
         * 更新 登录信息
         */
        $user->login_ip     = request()->ip();
        $user->login_time   = time();
        $user->save();
        /**
         * 写入 session 信息
         */
        session(self::USER_KEY_STR,[
            'username'      =>  $user->username,
            'admin_id'      =>  $user->admin_id,
        ]);
        return ['error' =>  false,'message' =>  '登录成功！'];
    }

    /** 检测 是否登录
     * @return mixed
     */
    public static function check_login(){
        return session('?'.self::USER_KEY_STR);
    }

    /** 获取登录 用户信息
     * @return mixed
     */
//    public static function getUserInfo($str = ''){
//        $str = mb_strlen($str)?'.'.$str:$str;
//        return session(self::USER_KEY_STR.$str);
//    }
    public static function getUserInfo(){
        return session(self::USER_KEY_STR);
    }

    /** 获取器 之 格式化 login_time
     * @param $value
     * @return false|string
     */
    public function getLoginTimeAttr($value){
        return date('Y-m-d H:i:s',$value);
    }

    /** 获取器 之 格式化 is_lock
     * @param $value
     * @return string
     */
    public function getIsLockTextAttr($value){
        return $value?'正常':'锁定';
    }

    public function authGroup()
    {
//        return $this->belongsToMany('auth_group','auth_group_access','admin_id','admin_id');
        return $this->belongsToMany('auth_group','auth_group_access');
    }



}